package com.ldc.wandroid.ui.fragments;

import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.ldc.common.mvvm.BaseMvvmFragment;
import com.ldc.common.utils.ViewModelUtils;
import com.ldc.wandroid.adapter.ProjectTabAdapter;
import com.ldc.wandroid.databinding.FragmentProjectTabBinding;
import com.ldc.wandroid.model.ProjectsModel;
import com.ldc.wandroid.viewmodel.ProjectTabViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * A simple {@link Fragment} subclass.
 */
public class ProjectTabFragment extends BaseMvvmFragment<FragmentProjectTabBinding, ProjectTabViewModel> {
    private ProjectTabAdapter projectTabAdapter;

    public static ProjectTabFragment newInstance() {
        Bundle args = new Bundle();
        ProjectTabFragment fragment = new ProjectTabFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        viewModel.getProjects().removeObserver(this::processProjects);
    }

    @Override
    protected FragmentProjectTabBinding initViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return FragmentProjectTabBinding.inflate(inflater, container, false);
    }

    @Override
    protected void main(Bundle savedInstanceState) {
        projectTabAdapter = new ProjectTabAdapter(getChildFragmentManager(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        // loading
        viewBinding.layoutPb.viewPd.setVisibility(Boolean.TRUE.equals(viewModel.getLoading().getValue()) ? View.VISIBLE : View.GONE);
        // 加载数据
        viewModel.getProjects().observeForever(this::processProjects);
        viewModel.loadProjects();


    }

    @Override
    protected ProjectTabViewModel initViewModel() {
        return ViewModelUtils.getViewModel(this, ProjectTabViewModel.class);
    }

    private void processProjects(List<ProjectsModel> models) {
        List<Fragment> fragments = new ArrayList<>();
        for (ProjectsModel item :
                models) {
            fragments.add(ProjectInfoFragment.newInstance(item.getName(), "" + item.getId()));
        }
        projectTabAdapter.setNewData(fragments, models);
        viewBinding.fragmentContainer.setCurrentItem(0);
        viewBinding.fragmentContainer.setOffscreenPageLimit(models.size() - 1);
        viewBinding.fragmentContainer.setAdapter(projectTabAdapter);

    }

}
